package com.example.myexperiment1;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.ScrollingMovementMethod;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;

public class MainActivity extends AppCompatActivity {
    Stack<Double> numberStack=new Stack<Double>();
    Stack<Character> symbolStack=new Stack<Character>();




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView_before=(TextView)findViewById(R.id.textView_before);
        TextView textView_after=(TextView)findViewById(R.id.textView_after);


        Spinner spinner_before=(Spinner)findViewById(R.id.spinner_before);
        Spinner spinner_after=(Spinner)findViewById(R.id.spinner_after);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.items, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner_before.setAdapter(adapter);
        ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this, R.array.item, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner_after.setAdapter(adapter);
        spinner_before.setAdapter(adapter1);//添加spinner用于选择是正常计算还是进制换算或者是单位换算


        Button button_clear=(Button)findViewById(R.id.button_clear);//所有按钮的监听器都在这块儿
        Button button_left=(Button)findViewById(R.id.button_left);
        Button button_right=(Button)findViewById(R.id.button_right);
        Button button_del=(Button)findViewById(R.id.button_del);
        Button button_add=(Button)findViewById(R.id.button_add);
        Button button_sub=(Button)findViewById(R.id.button_sub);
        Button button_mul=(Button)findViewById(R.id.button_mul);
        Button button_div=(Button)findViewById(R.id.button_div);
        Button button_1=(Button)findViewById(R.id.button_1);
        Button button_2=(Button)findViewById(R.id.button_2);
        Button button_3=(Button)findViewById(R.id.button_3);
        Button button_4=(Button)findViewById(R.id.button_4);
        Button button_5=(Button)findViewById(R.id.button_5);
        Button button_6=(Button)findViewById(R.id.button_6);
        Button button_7=(Button)findViewById(R.id.button_7);
        Button button_8=(Button)findViewById(R.id.button_8);
        Button button_9=(Button)findViewById(R.id.button_9);
        Button button_0=(Button)findViewById(R.id.button_0);
        Button button_power=(Button)findViewById(R.id.button_power);
        Button button_percent=(Button)findViewById(R.id.button_percent);
        Button button_point=(Button)findViewById(R.id.button_point);
        Button button_equal=(Button)findViewById(R.id.button_equal);
        Button button_cos=(Button)findViewById(R.id.button_cos);
        Button button_sin=(Button)findViewById(R.id.button_sin);
        Button button_operate=(Button)findViewById(R.id.button_operate);
        Button button_menu=(Button)findViewById(R.id.button_menu);
        StringBuilder str=new StringBuilder();

        button_0.setOnClickListener(view -> {
            str.append(0);
            textView_before.setText(str);
        });
        button_1.setOnClickListener(view -> {
            str.append(1);
            textView_before.setText(str);
        });
        button_2.setOnClickListener(view -> {
            str.append(2);
            textView_before.setText(str);
        });
        button_3.setOnClickListener(view -> {
            str.append(3);
            textView_before.setText(str);
        });
        button_4.setOnClickListener(view -> {
            str.append(4);
            textView_before.setText(str);
        });
        button_5.setOnClickListener(view -> {
            str.append(5);
            textView_before.setText(str);
        });
        button_6.setOnClickListener(view -> {
            str.append(6);
            textView_before.setText(str);
        });
        button_7.setOnClickListener(view -> {
            str.append(7);
            textView_before.setText(str);
        });
        button_8.setOnClickListener(view -> {
            str.append(8);
            textView_before.setText(str);
        });
        button_9.setOnClickListener(view -> {
            str.append(9);
            textView_before.setText(str);
        });
        button_left.setOnClickListener(view -> {
            str.append('(');
            textView_before.setText(str);
        });
        button_right.setOnClickListener(view -> {
            str.append(')');
            textView_before.setText(str);
        });
        button_point.setOnClickListener(view -> {
            str.append('.');
            textView_before.setText(str);
        });

        button_add.setOnClickListener(view -> {
            str.append('+');
            textView_before.setText(str);
        });

        button_sub.setOnClickListener(view -> {
            str.append('-');
            textView_before.setText(str);
        });

        button_mul.setOnClickListener(view -> {
            str.append('*');
            textView_before.setText(str);
        });

        button_div.setOnClickListener(view -> {
            str.append('/');
            textView_before.setText(str);
        });

        button_del.setOnClickListener(view -> {
            if(str.length()==0){
                str.delete(0,str.length());
                textView_before.setText(str);
            }
            else{
                str.deleteCharAt(str.length()-1);
                textView_before.setText(str);
            }

        });

        button_clear.setOnClickListener(view -> {
                str.delete(0,str.length());
                textView_before.setText(str);
        });

        button_power.setOnClickListener(view -> {
            str.append('^');
            textView_before.setText(str);
        });

        button_menu.setOnClickListener(view -> {
            menu();
        });

        button_sin.setOnClickListener(view -> {
            String R=null;
            R=evaluate(str.toString());
            Double S=Double.parseDouble(R);
            Double S1=Math.sin(S);
            textView_after.setText(S1.toString());
        });

        button_cos.setOnClickListener(view -> {
            String R=evaluate(str.toString());
            Double S=Double.parseDouble(R);
            Double S1=Math.cos(S);
            textView_after.setText(S1.toString());
        });

        button_equal.setOnClickListener(view -> {
            String R=evaluate(str.toString());
            textView_after.setText(R);
        });


        button_power.setOnClickListener(view -> {
            String R=evaluate(str.toString());
            Double P=Double.parseDouble(R)*Double.parseDouble(R);
            textView_after.setText(P.toString());
        });

        button_percent.setOnClickListener(view -> {
            String R=evaluate(str.toString());
            Double P=Double.parseDouble(R);
            Double S=P/100;
            textView_after.setText(S.toString());
        });

        button_operate.setOnClickListener(view -> {
            String string_before=spinner_before.getSelectedItem().toString();
            String string_after=spinner_after.getSelectedItem().toString();
            if(string_before.charAt(0)=='计'){
                Toast.makeText(MainActivity.this,"请选择合适的功能",Toast.LENGTH_LONG).show();
            }
            else if(string_before.charAt(0)=='1'&&string_before.charAt(1)=='0'){
                if(string_after.charAt(0)=='计'){
                    Toast.makeText(MainActivity.this,"请选择合适的功能",Toast.LENGTH_LONG).show();
                }
                else if(string_after.charAt(0)=='2'){
                    int s1=Integer.valueOf(textView_before.getText().toString());
                    String s2=Integer.toBinaryString(s1);
                    textView_after.setText(s2);
                }
                else if(string_after.charAt(0)=='8'){
                    int s1=Integer.valueOf(textView_before.getText().toString());
                    String s2=Integer.toOctalString(s1);
                    textView_after.setText(s2);
                }
                else if(string_after.charAt(0)=='1'&&string_after.charAt(1)=='6'){
                    int s1=Integer.valueOf(textView_before.getText().toString());
                    String s2=Integer.toHexString(s1);
                    textView_after.setText(s2);
                }
                else{
                    Toast.makeText(MainActivity.this,"请选择合适的功能",Toast.LENGTH_LONG).show();
                }
            }
            else if(string_before.charAt(0)=='米'){
                if(string_after.charAt(0)=='厘'&&string_after.charAt(1)=='米'){
                    String R=evaluate(str.toString());
                    Double P=Double.parseDouble(R);
                    Double S=P*100;
                    textView_after.setText(S.toString());
                }
                else if(string_after.charAt(0)=='毫'&&string_after.charAt(1)=='米'){
                    String R=evaluate(str.toString());
                    Double P=Double.parseDouble(R);
                    Double S=P*10000;
                    textView_after.setText(S.toString());
                }
                else if(string_after.charAt(0)=='米'){
                    textView_after.setText(textView_before.getText());
                }
            }
            else if(string_before.charAt(0)=='毫'&&string_before.charAt(1)=='米'){
                if(string_after.charAt(0)=='厘'&&string_after.charAt(1)=='米'){
                    String R=evaluate(str.toString());
                    Double P=Double.parseDouble(R);
                    Double S=P/100;
                    textView_after.setText(S.toString());
                }
                else if(string_after.charAt(0)=='毫'&&string_after.charAt(1)=='米'){
                    textView_after.setText(textView_before.getText());
                }
                else if(string_after.charAt(0)=='米'){
                    String R=evaluate(str.toString());
                    Double P=Double.parseDouble(R);
                    Double S=P/10000;
                    textView_after.setText(S.toString());
                }
            }
            else if(string_before.charAt(0)=='厘'&&string_before.charAt(1)=='米'){
                if(string_after.charAt(0)=='厘'&&string_after.charAt(1)=='米'){
                    textView_after.setText(textView_before.getText());
                }
                else if(string_after.charAt(0)=='毫'&&string_after.charAt(1)=='米'){
                    String R=evaluate(str.toString());
                    Double P=Double.parseDouble(R);
                    Double S=P*100;
                    textView_after.setText(S.toString());
                }
                else if(string_after.charAt(0)=='米'){
                    String R=evaluate(str.toString());
                    Double P=Double.parseDouble(R);
                    Double S=P/100;
                    textView_after.setText(S.toString());
                }
            }

        });


    }


    public void menu(){//菜单界面
        AlertDialog.Builder buider =new AlertDialog.Builder(MainActivity.this);
        buider.setMessage("请选择").setTitle("菜单界面");
        buider.setPositiveButton("帮助", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(MainActivity.this,"这是帮助",Toast.LENGTH_LONG).show();
            }
        });
        buider.setNegativeButton("退出", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(MainActivity.this,"退出",Toast.LENGTH_SHORT).show();
            }
        });
        buider.show();
    }

    public String evaluate(String express) {
        String expression = express;
        double calculate = 0;
        try {
            List<String> infixExpression = depositList(expression);//中缀表达式
            List<String> calculateExpression = parsExpression(infixExpression);//后缀表达式
            calculate = calculate(calculateExpression);
        }catch (RuntimeException e){
            return "error";
        }
        if (calculate==0){
            return "0";
        } else {
            BigDecimal bigDecimal = new BigDecimal(String.format("%.12f",calculate));//去掉前面多余的零
            String result = bigDecimal.toString();
            if(result.indexOf(".")>0){
                result = result.replaceAll("0+?$","");//去掉后面无用的零
                result = result.replaceAll("[.]$","");//如小数点后面全是零去掉小数点
            }
            return result;
        }
    }


    public static List<String> parsExpression(List<String> list) {//方法：将得到的中缀表达式对应的转换后缀表达式对应的List
        //定义两个栈
        Stack<String> s1 = new Stack<String>(); // 符号栈
        List<String> s2 = new ArrayList<String>(); // 储存中间结果的Lists2


        for(String item: list ) {
            if(item.matches("^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|[1-9]\\d*|0|-[1-9]\\d*\\.\\d*|-0\\.\\d*|-[1-9]\\d*$")) {//如果是一个数加入s2
                s2.add(item);
            } else if (item.equals("(")) {
                s1.push(item);
            } else if (item.equals(")")) {

                while(!s1.peek().equals("(")) {//如果是右括号“)”，则依次弹出s1栈顶的运算符，并压入s2，直到遇到左括号为止，此时将这一对括号丢弃
                    s2.add(s1.pop());
                }
                s1.pop();//将 ( 弹出 s1栈， 消除小括号
            } else {
                while(s1.size() != 0 && operation.getValue(s1.peek()) >= operation.getValue(item) ) {
                    s2.add(s1.pop());
                }

                s1.push(item);
            }
        }


        while(s1.size() != 0) {	//将s1中剩余的运算符依次弹出并加入s2
            s2.add(s1.pop());
        }

        return s2;

    }

    public static List<String> depositList(String s) {

        List<String> list = new ArrayList<String>();//定义一个List,存放中缀表达式 对应的内容
        int i = 0;
        String str;
        char c;
        do {
            boolean isMinus = false;
            if ((c=s.charAt(i))=='-'){
                if (i==0 || s.charAt(i-1)=='('){
                    isMinus=true;
                }
            }
            if(((c=s.charAt(i)) < 48 ||  (c=s.charAt(i)) > 57) && !isMinus) {
                list.add("" + c);
                i++;
            } else {
                str = ""; //先将str 置成""
                do {
                    str += c;
                    i++;
                }while(i < s.length() && (((c=s.charAt(i)) >= 48 && (c=s.charAt(i)) <= 57) || (c=s.charAt(i)) == '.'));
                list.add(str);
            }
        }while(i < s.length());
        return list;
    }

    public static double calculate(List<String> list) {
        Stack<String> stack = new Stack<String>();// 创建栈
        for (String item : list) {
            if (item.matches("^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|[1-9]\\d*|0|-[1-9]\\d*\\.\\d*|-0\\.\\d*|-[1-9]\\d*$")) { //使用正则表达式匹配多位数
                stack.push(item);
            } else {
                double num2 = Double.parseDouble(stack.pop());	// pop出两个数，并运算， 再入栈，如果空就赋值为零是为了让负数也能算
                double num1 = Double.parseDouble(stack.pop());
                double res = 0;
                if (item.equals("+")) {
                    res = num1 + num2;
                } else if (item.equals("-")) {
                    res = num1 - num2;
                } else if (item.equals("*")) {
                    res = num1 * num2;
                } else if (item.equals("/")) {
                    res = num1 / num2;
                } else {
                    throw new RuntimeException("运算符有误");
                }

                stack.push("" + res);
            }

        }

        return Double.parseDouble(stack.pop());
    }

}
//编写一个类 Operation 可以返回一个运算符 对应的优先级
class operation {
    private static int Add = 1;
    private static int Sub = 1;
    private static int Mul = 2;
    private static int Div = 2;

    //写一个方法，返回对应的优先级数字
    public static int getValue(String operation) {
        int result = 0;
        switch (operation) {
            case "+":
                result = Add;
                break;
            case "-":
                result = Sub;
                break;
            case "*":
                result = Mul;
                break;
            case "/":
                result = Div;
                break;
            default:

                break;
        }
        return result;
    }


}
